<?php
/**
 * 合作伙伴 bos 清理事件监听
 *
 * Author: Zeon
 * Date: 2018/1/17
 * Created by Panxsoft.
 */
namespace App\Observers;



use App\Http\Models\Partner;
use App\Services\Utils\Bosable;

class PartnerObserver
{
    use Bosable;

    /**
     * @var Partner
     */
    private $model;

    const BOS_COLUMNS = ['logo'];

    /**
     * PartnerObserver constructor.
     * @param Partner $partner
     */
    public function __construct(Partner $partner)
    {
        $this->model = $partner;
    }

    /**
     *
     */
    public function updated()
    {
        $this->deleteBosKeys($this->changedOriginalBosKeys());
    }

    /**
     *
     */
    public function deleted()
    {
        $this->deleteBosKeys($this->originColumnsToBosKeys(self::BOS_COLUMNS));
    }

    /**
     * @param array $columns
     * @return array
     */
    private function originColumnsToBosKeys(array $columns)
    {
        return array_map([$this->model, 'getOriginal'], $columns);
    }

    /**
     * @param array $keys
     * @return array
     */
    private function deleteBosKeys(array $keys)
    {
        return array_map([$this, 'deleteBosKey'], $keys);
    }

    /**
     * 返回更新后已经改变的 bos keys
     * @return array
     */
    private function changedOriginalBosKeys()
    {
        $dirty_columns = array_keys($this->model->getDirty());

        $dirty_bos_columns = array_values(array_intersect(self::BOS_COLUMNS, $dirty_columns));

        $original_bos_keys = $this->originColumnsToBosKeys($dirty_bos_columns);

        return $original_bos_keys;
    }
}
